using System;
using System.Globalization;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;
using System.Reflection;
using JigLibX.Physics;
using JigLibX.Collision;
using Services;
using Utilities.Menu.UIElements;
using EnhancedTimer.Resources;
using Services.Menu;
using Utilities;

namespace EnhancedTimer
{
    
    class NewTimerMenu : DrawableGameComponent
    {

        //GraphicsDeviceManager GraphicsDeviceManager;
        InputManager input_manager;

        SpriteBatch spriteBatch;
        StateManager StateManager;
        protected float press_wait;
        protected readonly float PRESS_INTERVAL = 0.2f;
        MyButton title;
        MyButton exactTimeString;
        MyButton exactTimeButton, confirmButton;
        TimeSpan exactTimeSpan;
        //MyButton timeDownButton, timeUpButton;
        MyButton minutesButton, secondsButton, hoursButton, minutesString, secondsString, hoursString;

        public NewTimerMenu(Game game)
            : base(game)
        {
            //this.GraphicsDeviceManager = graphics;
        }

        public override void Initialize()
        {
            spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
            StateManager = Game.Services.GetService(typeof(AStateManager)) as StateManager;
            Resume();
            base.Initialize();
        }
        public void Resume()
        {
            Game.Services.RemoveService(typeof(IInputManager));
            input_manager = new InputManager(Game);
            Game.Components.Add(input_manager);
            input_manager.OnTap += on_tap;
        }
        protected override void LoadContent()
        {
            var titleFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Title");
            var font = Game.Content.Load<SpriteFont>("Fonts/SegoeWP");
            var box = Game.Content.Load<Texture2D>("bar_box");
            var white = Game.Content.Load<Texture2D>("WhitePixel");

            title = new MyButton(new Rectangle(0, 0, 480, 150), Strings.NewTimerMenu, Color.White, titleFont);
            //timeDownButton = new MyButton(new Rectangle(260, 180, 180, 60), Strings.TimeDown, Color.Green, font);
            //timeUpButton = new MyButton(new Rectangle(260, 180, 180, 60), Strings.TimeUp, Color.Green, font);

            exactTimeString = new MyButton(new Rectangle(10, 200, 460, 80), Strings.AlertAt, Color.White, font, TextPos.Left);
            exactTimeButton = new MyButton(new Rectangle(10, 280, 460, 80), "", Color.Black,font, TextPos.Center, white,Color.LightGray);

            //remainingTimeString = new MyButton(new Rectangle(10, 400, 460, 80), Strings.AlertIn, Color.White, font, TextPos.Left);
            //remainingTimeButton = new MyButton(new Rectangle(10, 480, 460, 80), "", Color.Black, font, TextPos.Center, white, Color.LightGray);

            confirmButton = new MyButton(new Rectangle(260, 720, 180, 60), Strings.Confirm, Color.White, font, TextPos.Center, box, Color.White);

            minutesString = new MyButton(new Rectangle(165, 480, 140, 80), Strings.Minutes, Color.White, font);
            secondsString = new MyButton(new Rectangle(325, 480, 140, 80), Strings.Seconds, Color.White, font);
            hoursString = new MyButton(new Rectangle(15, 480, 140, 80), Strings.Hours, Color.White, font);

            minutesButton = new MyButton(new Rectangle(165, 560, 140, 80), "", Color.Black, font, TextPos.Center, white, Color.LightGray);
            secondsButton = new MyButton(new Rectangle(325, 560, 140, 80), "", Color.Black, font, TextPos.Center, white, Color.LightGray);
            hoursButton = new MyButton(new Rectangle(15, 560, 140, 80), "", Color.Black, font, TextPos.Center, white, Color.LightGray);

            //timeDownButton.enabled = true;
            //timeUpButton.enabled = false;
            //UpdateObjects();
            base.LoadContent();
        }
        protected override void Dispose(bool disposing)
        {
            Game.Services.RemoveService(typeof(IInputManager));
            base.Dispose(disposing);
        }

        
        public override void Update(GameTime gameTime)
        {
            if (press_wait < PRESS_INTERVAL)
                press_wait += (float)gameTime.ElapsedGameTime.TotalSeconds;
            
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                StateManager.Resume(false);
            } 
            base.Update(gameTime);
        }


        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            
            spriteBatch.Begin();

            title.Draw(spriteBatch);
            exactTimeButton.Draw(spriteBatch);
            exactTimeString.Draw(spriteBatch);

            hoursString.Draw(spriteBatch);
            hoursButton.Draw(spriteBatch);

            minutesButton.Draw(spriteBatch);
            minutesString.Draw(spriteBatch);

            secondsButton.Draw(spriteBatch);
            secondsString.Draw(spriteBatch);

            confirmButton.Draw(spriteBatch);

            spriteBatch.End();
            base.Draw(gameTime);
        }

        void closeSelector(DateTime timeSpan)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            exactTimeSpan = timeSpan.TimeOfDay;
            var s = "";
            if (exactTimeSpan.Hours < 9)
                s = "0";
            s += exactTimeSpan.Hours + ":";
            if (exactTimeSpan.Minutes < 9)
                s += "0";
            s += exactTimeSpan.Minutes + ":";
            if (exactTimeSpan.Seconds < 9)
                s += "0";
            s += exactTimeSpan.Seconds;
            exactTimeButton.text = s;
        }
        void abortSelector()
        {
            this.Enabled = true;
            input_manager.Enabled = true;
        }
        void on_tap(Vector2 tap_position)
        {
            if (press_wait < PRESS_INTERVAL) return;
            if (confirmButton.tapped_on(tap_position))
            {
                CreateNewTimer();
            }
            
            else if (exactTimeButton.tapped_on(tap_position))
            {
                secondsButton.text = "";
                minutesButton.text = "";
                hoursButton.text = "";
                this.Enabled = false;
                input_manager.Enabled = false;
                var now = DateTime.Now;
                StateManager.OpenHourSelector(closeSelector, abortSelector, new TimeSpan(now.Hour, now.Minute, now.Second), Strings.ChoseHour);
            }
            else if (secondsButton.tapped_on(tap_position))
            {
                exactTimeButton.text = "";
                OpenKeyboard(secondsButton);
            }
            else if (minutesButton.tapped_on(tap_position))
            {
                exactTimeButton.text = "";
                OpenKeyboard(minutesButton);
            }
            else if (hoursButton.tapped_on(tap_position))
            {
                exactTimeButton.text = "";
                OpenKeyboard(hoursButton);
            }
        }
        MyButton activeButton;
        void OpenKeyboard(MyButton button)
        {
            activeButton = button;
            Guide.BeginShowKeyboardInput(
                   PlayerIndex.One,
                   Strings.AlertIn,
                   Strings.Hours,
                   button.text,
                   new AsyncCallback(OnEndShowKeyboardInput),
                   null);
        }
        private void OnEndShowKeyboardInput(IAsyncResult result)
        {
            if (result != null && Guide.EndShowKeyboardInput(result) != null && activeButton!=null)
            {
                activeButton.text = Guide.EndShowKeyboardInput(result);
                activeButton = null;
            }

            try
            {
                int hours = Int32.Parse(hoursButton.text);
                if (hours < 0 || hours > 24)
                    hoursButton.textColor = Color.Red;
                else
                    hoursButton.textColor = Color.Black;
            }
            catch (Exception e)
            {
                e.ToString();
                hoursButton.textColor = Color.Red;
            }

            try
            {
                int min = Int32.Parse(minutesButton.text);
                if (min < 0 || min > 59)
                    minutesButton.textColor = Color.Red;
                else
                    minutesButton.textColor = Color.Black;
            }
            catch (Exception e)
            {
                e.ToString();
                minutesButton.textColor = Color.Red;
            }
            try
            {
                int sec = Int32.Parse(secondsButton.text);
                if (sec < 0 || sec > 59)
                    secondsButton.textColor = Color.Red;
                else
                    secondsButton.textColor = Color.Black;
            }
            catch (Exception e)
            {
                e.ToString();
                secondsButton.textColor = Color.Red;
            }
        }
        void CreateNewTimer()
        {
            int hours = 0, min = 0, sec = 0;
            if (exactTimeButton.text == "")
            {
                
                bool error = false;
                try
                {
                    hours = hoursButton.text == "" ? 0 : Int32.Parse(hoursButton.text);
                    if (hours < 0 || hours > 24)
                        hoursButton.textColor = Color.Red;
                    else
                        hoursButton.textColor = Color.Black;
                }
                catch (Exception e)
                {
                    error = true;
                    e.ToString();
                    hoursButton.textColor = Color.Red;
                }

                try
                {
                    min = minutesButton.text == "" ? 0 : Int32.Parse(minutesButton.text);
                    if (min < 0 || min > 59)
                        minutesButton.textColor = Color.Red;
                    else
                        minutesButton.textColor = Color.Black;
                }
                catch (Exception e)
                {
                    error = true;
                    e.ToString();
                    minutesButton.textColor = Color.Red;
                }
                try
                {
                    sec = secondsButton.text == "" ? 0 : Int32.Parse(secondsButton.text);
                    if (sec < 0 || sec > 59)
                        secondsButton.textColor = Color.Red;
                    else
                        secondsButton.textColor = Color.Black;
                }
                catch (Exception e)
                {
                    error = true;
                    e.ToString();
                    secondsButton.textColor = Color.Red;
                }
                if (error)
                    return;
                if (hours == 0 && min == 0 && sec == 0)
                {
                    StateManager.Resume(false);
                    return;
                }
                TimeSpan time = new TimeSpan(hours, min, sec);
                StateManager.SetNewTimer(time, TimerStatus.RunningDown);
            }
            else
            {
                //TimeSpan current = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                TimeSpan current = DateTime.Now.TimeOfDay;
                if (current > exactTimeSpan)
                    exactTimeSpan += new TimeSpan(1, 0, 0, 0);
                var time2 = exactTimeSpan - current;
                if (time2 == TimeSpan.Zero)
                {
                    StateManager.Resume(false);
                    return;
                }
                StateManager.SetNewTimer(time2, TimerStatus.RunningDown);
            }
            
            
            
        }
        void UpdateObjects()
        {
            /*if (!timeDownButton.enabled)
            {
                exactTimeButton.enabled = false;
                
                exactTimeString.enabled = false;
                
            }
            else
            {
                exactTimeButton.enabled = true;
     
                exactTimeString.enabled = true;

            }*/
        }
    }
}
